//
//  CYCompanyRegisterTableVC.m
//  CreditAddressBook
//
//  Created by LE on 15/12/15.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYCompanyRegisterTableVC.h"
#import "LEBarButtonItem.h"
#import "LEImagePicker.h"
#import "CYLoginHttpTool.h"
#import "CYJsonInfo.h"
#import "MJExtension.h"
#import "MBProgressHUD+MJ.h"
#import "GCD.h"
#import "LEProgressButton.h"
#import "CYCompanyRegParam.h"
#import "CYJumpsTool.h"
#import "CYEscape.h"

@interface CYCompanyRegisterTableVC ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *userNameTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UITextField *rePasswordTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneCodeTF;
@property (weak, nonatomic) IBOutlet UILabel *sendSMSLabel;

@property(nonatomic, strong) LEImagePicker *imagePicker;
@property(nonatomic, strong) GCDTimer *GCDTimer;

@property(nonatomic, strong) CYCompanyRegParam *regParam;
@end

@implementation CYCompanyRegisterTableVC

- (CYCompanyRegParam *)regParam {
    if (!_regParam) {
        _regParam = [CYCompanyRegParam new];
    }
    return _regParam;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self submitBtn];
    self.imagePicker = [[LEImagePicker alloc] init];
}

- (void)submitBtn {
    LEBarButtonItem *item = [[LEBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Checked Checkbox 2-50"] andSelImage:[UIImage imageNamed:@"Checked Checkbox 2-50_h"] target:self action:@selector(submit)];
    self.navigationItem.rightBarButtonItem = item;
}

- (void)submit {
    [self.view.window endEditing:YES];
    if ([self setupParam]) {
        [MBProgressHUD showMessage:@"注册中" toView:self.view];
        if (!self.regParam.isNil) {
            [CYLoginHttpTool regeditCompanyWithParams:self.regParam success:^(NSString *message) {
                [MBProgressHUD hideHUDForView:self.view];
                [MBProgressHUD showSuccess:message];
                //登陆
                //            [CYLoginHttpTool companyLoginWithUserName:self.regParam.name andPassword:self.regParam.password success:^(NSString *message) {
                //
                //            } failure:^(NSString *message, NSError *error) {
                //
                //            }];
                //跳转到主界面
                [CYJumpsTool jumpToMain:self.view];
            } failure:^(NSString *message, NSError *error) {
                [MBProgressHUD hideHUDForView:self.view];
                if (message) {
                    [MBProgressHUD showError:message];
                } else if (error) {
                    [MBProgressHUD showError:@"服务器连接错误"];
                }
            }];
        }
    }
}

- (BOOL)setupParam {
    if (self.userNameTF.text && !self.userNameTF.text.isEmpty) {
        self.regParam.name = self.userNameTF.text;
    } else {
        [MBProgressHUD showError:@"请输入用户名"];
        return NO;
    }
    if (self.passwordTF.text && !self.passwordTF.text.isEmpty && [self.passwordTF.text equals:self.rePasswordTF.text]) {
        self.regParam.password = [CYEscape encrypt:self.passwordTF.text];
    } else {
        [MBProgressHUD showError:@"请输入密码"];
        return NO;
    }
    if (self.phoneCodeTF.text && !self.phoneCodeTF.text.isEmpty) {
        self.regParam.phoneCode = self.phoneCodeTF.text;
    } else {
        [MBProgressHUD showError:@"请输入验证码"];
        return NO;
    }
    if (self.phoneTF.text && !self.phoneTF.text.isEmpty) {
        self.regParam.phone = self.phoneTF.text;
    } else {
        [MBProgressHUD showError:@"请输入电话号码"];
        return NO;
    }
    if (!self.regParam.licenseAddress || self.regParam.licenseAddress.isEmpty) {
        [MBProgressHUD showError:@"请上传营业执照"];
        return NO;
    }
    if (!self.regParam.legalLicenseZAddress || self.regParam.legalLicenseZAddress.isEmpty) {
        [MBProgressHUD showError:@"请上传身份证正面照"];
        return NO;
    }
    if (!self.regParam.legalLicenseFAddress || self.regParam.legalLicenseFAddress.isEmpty) {
        [MBProgressHUD showError:@"请上传身份证反面照"];
        return NO;
    }
    return YES;
}

- (IBAction)idCardZ:(LEProgressButton *)sender {
    [self.view.window endEditing:YES];
    CYWeakObject(weakself, self);
    [self.imagePicker showInController:self handler:^(UIImage *image) {
        [weakself uploadImage:image button:sender completion:^(NSString *imagePath) {
            weakself.regParam.legalLicenseZAddress = imagePath;
        }];
    }];
}

- (IBAction)idCardF:(LEProgressButton *)sender {
    [self.view.window endEditing:YES];
    CYWeakObject(weakself, self);
    [self.imagePicker showInController:self handler:^(UIImage *image) {
        [weakself uploadImage:image button:sender completion:^(NSString *imagePath) {
            weakself.regParam.legalLicenseFAddress = imagePath;
        }];
    }];
}

- (IBAction)licenseBtn:(LEProgressButton *)sender {
    [self.view.window endEditing:YES];
    CYWeakObject(weakself, self);
    [self.imagePicker showInController:self handler:^(UIImage *image) {
        [weakself uploadImage:image button:sender completion:^(NSString *imagePath) {
            weakself.regParam.licenseAddress = imagePath;
        }];
    }];
}

- (IBAction)sendSMSBtn:(UIButton *)sender {
    [self.view.window endEditing:YES];
    if (self.phoneTF.text && !self.phoneTF.text.isEmpty) {
        //确认网络有连接后发送短信验证码
        [CYLoginHttpTool sendSMSWithPhone:self.phoneTF.text success:^(id json) {
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            if (jsonInfo.isSuccess) {
                [MBProgressHUD showSuccess:jsonInfo.message];
                [self countdown:sender];
            }else {
                [MBProgressHUD showError:jsonInfo.message];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD showError:CYServerConnectFailure];
            CYLog(@"服务器链接失败：%@", error);
        }];
    } else {
        [MBProgressHUD showError:@"请输入电话号码"];
    }
}

/**
 *  倒计时
 */
- (void)countdown:(UIButton *)btn {
    self.GCDTimer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    CYWeakObject(weakself, self);
    __block int time = 59;
    [self.GCDTimer event:^{
        if (time < 1) {
            //设置界面的按钮显示 根据自己需求设置
            weakself.sendSMSLabel.text = @"获取验证码";
            weakself.sendSMSLabel.textColor = [UIColor blackColor];
            btn.userInteractionEnabled = YES;
            [weakself.GCDTimer destroy];
        } else {
            weakself.sendSMSLabel.text = CYStringFormat(@"%ds后重试", time);
            weakself.sendSMSLabel.textColor = [UIColor grayColor];
            btn.userInteractionEnabled = NO;
        }
        time--;
    } timeInterval:NSEC_PER_SEC * 1];
    [self.GCDTimer start];
}
/**
 *  图片上传
 */
- (void)uploadImage:(UIImage *)image button:(LEProgressButton *)btn completion:(void (^)(NSString *imagePath))completion {
    [btn setImage:image forState:UIControlStateNormal];
    [CYHttpTool postWithURL:[CYURL updateHeadPicrPath] params:nil image:image success:^(id json) {
        //上传成功更新图片访问路径
        if ([json[@"success"] isEqualToString:@"success"]) {
            btn.ratio = 1;
            if (completion) {
                completion(json[@"message"]);
            }
        } else {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:json[@"message"]];
            //清除图片显示数据
            [btn setImage:[UIImage imageNamed:@"icon_btn_add_unpressed"] forState:UIControlStateNormal];
        }
    } failure:^(NSError *error) {
        CYLog(@"头像上传服务器连接失败：%@", error);
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:CYServerConnectFailure];
        //清除图片显示数据
        [btn setImage:[UIImage imageNamed:@"icon_btn_add_unpressed"] forState:UIControlStateNormal];
    } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
//        CYLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
        CGFloat a = totalBytesWritten;
        CGFloat b = totalBytesExpectedToWrite;
        btn.ratio = a/b - 0.01;
    }];
}

#pragma mark - Table view data source

#pragma mark - delegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
//    CYLog(@"用户: %@", textField.text);
    if (textField.text && !textField.text.isEmpty) {
        if (textField.tag == 0) {
            //检测用户名是否可用
            [CYLoginHttpTool checkCarCompanyUserWithCompanyAccount:textField.text success:^{
                //            [MBProgressHUD showSuccess:@"可用"];
            } failure:^(NSString *message, NSError *error) {
                if (message) {
                    [MBProgressHUD showError:message];
                    textField.text = nil;
                }
            }];
        } else if (textField.tag == 1) {
            if (![textField.text equals:self.passwordTF.text]) {
                textField.text = nil;
                self.passwordTF.text = nil;
                [MBProgressHUD showError:@"两次密码输入不一致，请重新输入"];
                
            }
        }
    }
}
@end
